package org.jeecg.modules.demo.meal.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.vo.Result;
import org.jeecg.modules.demo.meal.entity.Meal;
import org.jeecg.modules.demo.meal.entity.MealSum;
import org.jeecg.modules.demo.meal.entity.OrderMeal;
import org.jeecg.modules.demo.meal.service.IMealSumService;
import org.jeecg.modules.demo.meal.service.IOrderMealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;

/**
 * @Description: 自定义订餐模块功能
 * @Author: jeecg-boot
 * @Date: 2021-06-10
 * @Version: V1.0
 */
@Api(tags = "订餐表")
@RestController
@RequestMapping("/meal/order")
@Slf4j
public class OrderController {
    @Autowired
    private IOrderMealService orderMealService;
    @Autowired
    private IMealSumService mealSumService;

    /**
     * 通过用户id和时间，查询本周的订餐情况
     *
     * @param empId
     * @param currentTime
     * @return
     */
    @PostMapping("/getMealListByIdAndTime")
    public Result<List<OrderMeal>> getMealListByIdAndTime(String empId,Date currentTime) {
        Result<List<OrderMeal>> result = new Result<>();
        QueryWrapper<OrderMeal> queryWrapper = new QueryWrapper();
        queryWrapper.eq("emp_id", empId);
        List<OrderMeal> mealList = orderMealService.list(queryWrapper);
        //获取日历，并把周一改为每周的开始时间
        Calendar calendar = Calendar.getInstance();
        calendar.setFirstDayOfWeek(Calendar.MONDAY);

        calendar.setTime(currentTime);
        List<OrderMeal> orderMeals = new ArrayList<>();
        //判断时间是这个月的第几周
        int week = calendar.get(Calendar.WEEK_OF_MONTH);
        for (OrderMeal orderMeal : mealList) {
            calendar.setTime(orderMeal.getUseMealTime());
            //查询出同一周的时间订餐信息
            if (week == calendar.get(Calendar.WEEK_OF_MONTH)) {
                orderMeals.add(orderMeal);
            }
        }
        result.setResult(orderMeals);
        return result;
    }

    @RequestMapping("/submitMeals")
    public Result<?> submitMeals(@RequestBody List<OrderMeal> orderMealList) {
        for (OrderMeal orderMeal : orderMealList) {
            if (orderMeal != null) {
                sumbitOrderMeal(orderMeal);
            }
        }
        return Result.OK("数据提交成功");
    }
    /**
     * 提交订餐信息
     * @param orderMeal
     * @return
     */
    public Result<?> sumbitOrderMeal(OrderMeal orderMeal) {
        System.out.println(orderMeal);
        //从数据库中获取当前订餐信息
        QueryWrapper<OrderMeal> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("use_meal_time", orderMeal.getUseMealTime());
        queryWrapper.eq("emp_id", orderMeal.getEmpId());
        OrderMeal dbOrderMeal = orderMealService.getOne(queryWrapper);

        //获取原有的订餐汇总表
        QueryWrapper<MealSum> queryWrapper2 = new QueryWrapper();
        queryWrapper2.eq("meal_time", orderMeal.getUseMealTime());
        MealSum dbMealSum = mealSumService.getOne(queryWrapper2);
        //判断对当前数组是保存还是修改
        if (dbOrderMeal != null) {
            //更新订餐汇总表、订餐表
            updateMealSumAndOrderMeal(orderMeal, dbOrderMeal, dbMealSum);
            return Result.OK("数据修改成功");
        } else {
            //新增订餐汇总表、订餐表
            addMealSumAndOrderMeal(orderMeal, dbMealSum);
            return Result.OK("数据添加成功");
        }

    }
    /**
     * 更新订餐表和汇总信息表的数据
     *
     * @param orderMeal
     */
    public void updateMealSumAndOrderMeal(OrderMeal orderMeal, OrderMeal dbOrderMeal, MealSum dbMealSum) {

        //获取原有的订餐表数据的内容
        //数据库是 没有订餐 -> 订餐，订餐 -> 没有订餐
        Integer dbLunch = dbOrderMeal.getLunch();
        Integer dbDinner = dbOrderMeal.getDinner();
        //状态没有改变，不需要更改
        if (dbLunch.equals(orderMeal.getLunch()) && dbDinner.equals(orderMeal.getDinner())) {

        } else {
            //状态改变
            //午餐改变
            if (!dbLunch.equals(orderMeal.getLunch())) {
                //1 -> 0
                if (dbLunch > 0 && orderMeal.getLunch().intValue() == 0 && dbLunch.intValue() == 1) {
                    dbMealSum.setLunchNo(dbMealSum.getLunchNo() - 1);
                }
                //0 ->  1
                else if (orderMeal.getLunch().intValue() == 1 && dbLunch.intValue() == 0) {
                    dbMealSum.setLunchNo(dbMealSum.getLunchNo() + 1);
                }
            }
            //晚餐改变
            if (!dbDinner.equals(orderMeal.getDinner())) {
                //1 -> 0
                if (dbDinner > 0 && orderMeal.getDinner().intValue() == 0 && dbDinner.intValue() == 1) {
                    dbMealSum.setDinnerNo(dbMealSum.getDinnerNo() - 1);
                }
                //0 ->  1
                else if (orderMeal.getDinner().intValue() == 1 && dbDinner.intValue() == 0) {
                    dbMealSum.setDinnerNo(dbMealSum.getDinnerNo() + 1);
                }
            }
        }
        //更新订餐表的数据
        dbOrderMeal.setLunch(orderMeal.getLunch());
        dbOrderMeal.setDinner(orderMeal.getDinner());
        orderMealService.updateById(dbOrderMeal);
        //更新订餐汇总表的数据内容
        mealSumService.updateById(dbMealSum);
    }

    /**
     * 保存订餐表和汇总信息表的数据
     *
     * @param orderMeal
     */
    public void addMealSumAndOrderMeal(OrderMeal orderMeal, MealSum dbMealSum) {
        //生产订餐汇总订餐表

        //没有添加新增汇总信息表的数据
        if (dbMealSum == null) {
            MealSum mealSum = new MealSum();
            mealSum.setMealTime(orderMeal.getUseMealTime());
            mealSum.setLunchNo(0);
            mealSum.setDinnerNo(0);
            if (orderMeal.getLunch().intValue() == 1) {
                mealSum.setLunchNo(1);
            }
            if (orderMeal.getDinner().intValue() == 1) {
                mealSum.setDinnerNo(1);
            }
            mealSumService.save(mealSum);

        } else {
            //已存在汇总信息表，更新数据
            if (orderMeal.getLunch().intValue() == 1) {
                dbMealSum.setLunchNo(dbMealSum.getLunchNo() + 1);
            }
            if (orderMeal.getDinner().intValue() == 1) {
                dbMealSum.setDinnerNo(dbMealSum.getDinnerNo() + 1);
            }
            mealSumService.updateById(dbMealSum);
        }

        //添加数据
        //调用添加函数
        orderMealService.save(orderMeal);
    }

    /**
     * 根据用餐类型 获取用户订阅午餐、晚餐的列表信息
     * @param type
     * @return
     */
    @PostMapping("/getOrderMealByTypeAndTime")
    public Result<List<OrderMeal>> getOrderMealByTypeAndTime(Integer type,Date currentTime) {
        Result<List<OrderMeal>> result = new Result<>();
        if (type != null ) {
            if (type.intValue() == 1) {
                QueryWrapper<OrderMeal> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("lunch",1);
                queryWrapper.eq("use_meal_time",currentTime);
                List<OrderMeal> list = orderMealService.list(queryWrapper);
                if (list != null && list.size() > 0) {
                    result.setResult(list);
                }else{
                    result.error500("暂无用户订餐");
                }
            } else {
                QueryWrapper<OrderMeal> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("dinner",1);
                queryWrapper.eq("use_meal_time",currentTime);
                List<OrderMeal> list = orderMealService.list(queryWrapper);
                if (list != null && list.size() > 0) {
                    result.setResult(list);
                }else{
                    result.error500("暂无用户订餐");
                }
            }
        }
        return result;
    }

    /**
     * 获取一周内的所有订餐信息情况，包括厨房用户和普通用户
     * @param userCode
     * @param userId
     * @param currentTime
     * @return
     */
    @RequestMapping("/getMealOfWeek")
    public Result<?> getMealOfMonth(String userCode, String userId,Date currentTime) {
        //厨房用户
        if (userCode.equals("cook") && userCode != null) {
            //厨房用户
            List<MealSum> sumList = mealSumService.list();
            //定义日历时间，并把周一设置周的开始
            Calendar calendar = Calendar.getInstance();
            calendar.setFirstDayOfWeek(Calendar.MONDAY);
            calendar.setTime(currentTime);
            //获取当前月的周数
            int week = calendar.get(Calendar.WEEK_OF_MONTH);
            List<Meal> weekList = new ArrayList<>();
            for (int i = 0; i < sumList.size(); i++) {
                calendar.setTime(sumList.get(i).getMealTime());
                int dbWeek = calendar.get(Calendar.WEEK_OF_MONTH);
                //周数相等，则获取该周份的所有数据信息
                if (week == dbWeek) {
                    MealSum tmpMealSum = sumList.get(i);
                    Meal meal = new Meal(tmpMealSum.getLunchNo(),tmpMealSum.getDinnerNo(),tmpMealSum.getMealTime());
                    weekList.add(meal);
                }
            }
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("list",weekList);
            jsonObject.put("usercode","cook");
            return Result.OK(jsonObject.toJSONString());
        } else {
            //普通用户
            QueryWrapper<OrderMeal> queryWrapper = new QueryWrapper<>();
            //限制该用户的id数据集合
            queryWrapper.eq("emp_id",userId);
            List<OrderMeal> sumList = orderMealService.list(queryWrapper);
            //定义日历时间，并把周一设置周的开始
            Calendar calendar = Calendar.getInstance();
            calendar.setFirstDayOfWeek(Calendar.MONDAY);
            calendar.setTime(currentTime);
            //当前月的周数
            int week = calendar.get(Calendar.WEEK_OF_MONTH);
            List<Meal> weekList = new ArrayList<>();
            for (int i = 0; i < sumList.size(); i++) {
                calendar.setTime(sumList.get(i).getUseMealTime());
                int dbWeek = calendar.get(Calendar.WEEK_OF_MONTH);
                //周数相等，则获取该周份的所有数据信息
                if (week == dbWeek) {
                    OrderMeal tmpOrderMeal = sumList.get(i);
                    Meal meal = new Meal(tmpOrderMeal.getLunch(),tmpOrderMeal.getDinner(),tmpOrderMeal.getUseMealTime());
                    weekList.add(meal);
                }
            }
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("list",weekList);
            jsonObject.put("usercode","order");
            return Result.OK(jsonObject.toJSONString());
        }
    }
}
